<?php
/**
 * Created by PhpStorm.
 * User: envision
 * Date: 2018-09-27
 * Time: 15:12
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Models\Destination;
use App\Models\Journey;
use Illuminate\Http\Request;

class DestinationController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = $request->pageSize ? $request->pageSize : 20;
        $sql = Destination::select();
        $data = $sql->orderBy('sort')->paginate($pageSize)->toArray();
        $result['destinationList'] = $data['data'];
        $result['totalNum'] = $data['total'];
        return $this->apiResponse($result);
    }

    public function show($destinationId)
    {
        $data = Destination::find($destinationId);
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {

        $data = $request->only(['destinationId', 'destinationPlace', 'destinationImg']);
        $destinationId = $data['destinationId'];
        unset($data['destinationId']);
        if($destinationId){
            $status = Destination::where('destinationId',$destinationId)->update($data);
        }else{
            $data['createTime'] = date('Y-m-d');
            $status = Destination::create($data);
        }
        if(!$status){
            return $this->apiResponse('', config('errorCode.UPDATE_FAILED'));
        }
        return $this->apiResponse('');
    }

    public function destroy($destinationId)
    {
        $destination = Destination::find($destinationId);
        $res = Journey::where('destinationPlace',$destination['destinationPlace'])->count();
        if ($res){
            return $this->apiResponse('', config('errorCode.PRODUCT_DELETE_FAILED'));
        }
        Destination::destroy($destinationId);
        return $this->apiResponse('');
    }

    public function sort(Request $request)
    {
        $data = $request->goalPlaceList;
        foreach ($data as $k=>$v){
            $status = Destination::where('destinationId',$v['destinationId'])->update(['sort' => $k]);
            if (!$status){
                return $this->apiResponse('',config('errorCode.UPDATE_FAILED'));
            }
        }
        return $this->apiResponse('');
    }
}